﻿using System;
using System.ComponentModel;
using System.Windows.Forms;
using QuanLyThongTinCoSo.BaseForm;
using QuanLyThongTinCoSo.Biz;

namespace QuanLyThongTinCoSo.Forms
{
    public partial class frmDangNhap : frmObject
    {
        private static frmDangNhap m_oInstance = null;

        public frmDangNhap()
        {
            InitializeComponent();

            InitDatabaseContext();
        }

        public static frmDangNhap GetInstance()
        {
            if (m_oInstance == null)
            {
                m_oInstance = new frmDangNhap();
            }
            return m_oInstance;
        }

        /// <summary>
        /// Check Control
        /// </summary>
        /// <returns></returns>
        private bool Validation()
        {
            var isValid = true;
           
            if (string.IsNullOrEmpty(txtUsername.Text))
            {
                errorProvider.SetError(this.txtUsername, "Tên đăng nhập không được để trống");
                isValid = false;
            }
            if (string.IsNullOrEmpty(txtPassword.Text))
            {
                errorProvider.SetError(this.txtPassword, "Mật khẩu không được để trống");
                isValid = false;
            }

            return isValid;
        }
        
        private void btnThoat_Click(object sender, EventArgs e)
        {
            try
            {
                Application.Exit();
            }
            catch (Exception)
            {                
            }
        }

        private void Login(object sender, EventArgs e)
        {
            var isValid = Validation();
            if (isValid)
            {
                var biz = new UserBiz();
                //if (biz.CheckUserLogin(txtUsername.Text, txtPassword.Text))
                {
                    var frm = new frmMain();
                    frm.Show();
                    Hide();
                }
                //else
                {
                    //TODO throw error message
                }                
            }            
        }

        private void frmDangNhap_FormClosed(object sender, FormClosedEventArgs e)
        {
            foreach (Form openForm in Application.OpenForms)
            {
                openForm.Close();
            }
            Application.Exit();
        }

        private void InitDatabaseContext()
        {
            BackgroundWorker bw = new BackgroundWorker();

            // this allows our worker to report progress during work
            bw.WorkerReportsProgress = true;

            // what to do in the background thread
            bw.DoWork += new DoWorkEventHandler(
            delegate(object o, DoWorkEventArgs args)
            {
                var biz = new RoleBiz();
                var roles = biz.GetAll();
            });

            bw.RunWorkerAsync();
        }
    }
}